﻿(function(){

	var pages = {
		'index': /^tag$/,
		'home': 'home',
		'hot': /^hot\/catalog$/,
		'my': 'my',
		'share/turnlist': 'mynologin',
		'detail': /^\d+\/\d+.shtml/,
		'new': 'new',
		'hotalbum': 'album',
		'albumdetail': /^album\/\d+\/\d+.shtml/,
		'tag': /^hot\/tag/,
		'profile': /^\d+$/,
		'login': /^login/,
		'pop': /^win\/se/,
		'register': /^reg/
	};
	var page_name = (function(){
		var path = (document.location.pathname).substring(1);
		if(document.location.host == 'hao.360.cn'){
			return 'daohang';
		} else {
			for(var key in pages){
				var it = pages[key];
				if(typeof it == 'string'){
					if(path == it) {
						return key;
					}
				} else {
					if(it.test(path)){
						return key;
					}
				}
			}
		}
		return 'opage';
	})();

	var win = window,
		doc = win.document,
		ref = doc.referrer,
		dom = doc.domain,
		agent = navigator.userAgent.toLowerCase(),
		url = location.href,
		encode = encodeURIComponent;

	var cookie = {
		get: function(name){
			var v = doc.cookie.match('(?:^|;)\\s*' + name + '=([^;]*)');
			return v ? decodeURIComponent(v[1]) : null;
	    },
	    set: function(name, value ,expires, path, domain){
	        var str = name + "=" + encodeURIComponent(value);
			if (expires !== null) {
				if (expires == 0) {expires = 100*365*24*60;}
				var exp = new Date();
				exp.setTime(exp.getTime() + expires*60*1000);
				str += "; expires=" + exp.toGMTString();
			}
			if (path) {str += "; path=" + path;}
			if (domain) {str += "; domain=" + domain;}
			document.cookie = str;
	    }
	};

	var guid = function() {
	    var S4 = function() {
	       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	    };
	    return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
	};

	var sid = (function(){
		var c = cookie.get('_sid');
		if(c) return c;
		var id = guid();
		cookie.set('_sid', id, null, '/');
		return id;
	})();

	var suid = function(mid){
		if(mid){
			cookie.set('_mid', mid, 0, '/');
		}
		var c = cookie.get('_suid');
		if(c) return c;
		var id = mid || guid();
		cookie.set('_suid', id, 0, '/');
		return id;
	};


	var bs = (function(){
		if(agent.indexOf('360se') > -1) return 'se';
		if(agent.indexOf('360ee') > -1) return 'ee';
		if(agent.indexOf('maxthon') > -1) return 'maxthon';
		if(agent.indexOf('se 1.x / se 2.x') > -1) return 'sogou';
		if(agent.indexOf('tencenttraveler') > -1) return 'tt';
		if(/chrome/i.test(agent) && /webkit/i.test(agent) && /mozilla/i.test(agent)) return 'chrome';
		if(/msie/i.test(agent) && !/opera/.test(agent)){
			var v = (agent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1];
			if(v < 7) return 'ie6';
			if(v < 8) return 'ie7';
			if(v < 9) return 'ie8';
			return 'ie9';
		} 
		if(/firefox/i.test(agent)) return 'ff';
		if(/webkit/i.test(agent)) return 'safari';
		if(/opera/i.test(agent)) return 'opera';
		return 'other';
	})();

	var getMod = function(el){
		while(el){
			var mod = el.getAttribute('module');
			if(mod) return mod;
			el = el.parentNode;
			if(!el || el.tagName.toLowerCase() == 'body') break;
		}
		return '';
	};

	var getParams = function(el){
		var tag = el.tagName.toLowerCase();
		if(tag == 'a'){
			var h = el.getAttribute('href') || '';
			if(h.indexOf('javascript') == 0 || h == '#'){
				h = '';
			} else {
				if(h.indexOf('http') && window._fr_ && h.indexOf('fr=') < 0){
					el.setAttribute('href', h.indexOf('?') > 0 ? (h + '&fr=' + window._fr_) : (h + '?fr=' + window._fr_));
				}
			}
			return {url: h, mt: el.getAttribute('module-tag') || el.getAttribute('id') || el.getAttribute('class') || '', title: el.textContent || el.innerText || el.getAttribute('title') || '', refer: url, m: getMod(el)};
		}
		if((tag == 'input' && (el.getAttribute('type').toLowerCase() == 'button' || el.getAttribute('type').toLowerCase() == 'submit')) || tag == 'button' ){
			return {url: 'button', mt: el.getAttribute('module-tag') || el.getAttribute('id') || el.getAttribute('class') || '', title: el.textContent || el.innerText || el.getAttribute('value') || '', refer: url, m: getMod(el)};
		}

		try{
			if(el.getAttribute('module-btn')){
				return {url: 'button', mt: el.getAttribute('module-btn') || '', title: el.textContent || el.innerText || el.getAttribute('title') || '', refer: url, m: getMod(el)};
			}
		}catch(ex){}

		el = el.parentNode;
		if(!el || !el.tagName || el.tagName.toLowerCase() == 'body'){
			return false;
		} else {
			return arguments.callee(el);
		}
	};

	var listener_click = function(e){
		e = e || win.event;
		var el = e.target || e.srcElement;
		var params = getParams(el);		
		if(!params) return;
		send(params, true);
	};

	var listener_load = function(){
		if(typeof PAGE_NAME != 'undefined'){
			page_name = PAGE_NAME;
		} 
		var ms = [];
		var divs = document.getElementsByTagName('div');
		for(var i = 0, il = divs.length; i < il; i++){
			var it = divs[i];
			if(it.getAttribute('module')){
				ms.push(it.getAttribute('module'));
			}
		}
		
		var params = {
			title: document.title,
			m: ms.join(',')
		};

		if(page_name == 'detail'){
			var tagEls = Como('a.info-tag-item');
			if(tagEls){
				var tag = [];
				for(var i = 0; i < tagEls.length; i++){
					tag.push(Como.String.trim(tagEls.get(i).text()));
				}
				params.tag = tag.join(',');	
			}
		}
		send(params, false)
	};

	var send = function(p, click){
		var params = {
			mid: '',
			qid: typeof ilike !="undefined" && ilike._baseData && ilike._baseData.qid ?  ilike._baseData.qid : "",
			sid: sid,
			url: url, refer: ref, br: bs, 
			action: click ? 1 : (window.page_out ? 2 : 0),
			p: page_name,
			m: '',
			title: '',
			tag: '',
			pid: window._fr_ ? window._fr_ : '',
			mt: '',
			_t: Math.random()
		};
		for(var i in p){
			params[i] = p[i].replace(/^\s+|\s+$/g, '');
		}
		params.url = encode(params.url);
		params.refer = encode(params.refer);
		params.title = encode(params.title);
		params.tag = encode(params.tag);
		params.mt = encode(decodeURIComponent(params.mt));
		//get mid from ilike_ext
		if(false){
		// if(typeof window._360ilike != 'undefined' && typeof window._360ilike.GetMid != 'undefined'){
		// 	params.mid = window._360ilike.GetMid();
		} else {
			var c = cookie.get('_mid');
			if(c){
				params.mid = c;
			} else {
				//get mid from se
				
				// if(typeof window.external != 'unknown' && typeof window.external != 'undefined' && typeof window.external.twGetSecurityID != 'undefined'){
				// 	var _mid = window.external.twGetSecurityID(window);
				// 	if(_mid) params.mid = window.external.GetSpecialData(_mid);
				// }
			}
		}
		params.suid = suid(params.mid);


		var re = [];
		for(var i in params){
			re.push(i + '=' + params[i]);
		}
		var img = new Image();
		img.src = 'http://s.360.cn/ilike/n.html?' + re.join('&');
		window['_stat_img' + Math.random()] = img;
	};

	var onReady = function(callback){
		if(doc.addEventListener){
			if(bs == 'safari'){
				var timeout = setInterval(function(){
					if(/loaded|complete/.test(doc.readyState)){
						callback();
						clearTimeout(timeout);
					}
				}, 3);
			} else {
				doc.addEventListener('DOMContentLoaded', callback, true);
			}
		} else {
			var src = 'javascript: void(0)';
			if(window.location.protocol == 'https:'){
				src = '//:';
			}
			window._ilike_stat_ = callback;
			document.write('<script onreadystatechange="if (this.readyState==\'complete\') {this.parentNode.removeChild(this);window._ilike_stat_();}" defer="defer" ' + 'src="' + src + '"><\/script\>');
		}
		//win.onload = callback;
	};
	if(typeof ilike_nopv == "undefined"){
		onReady(function(){
			setTimeout(function(){
				var body = doc.body;
				body.attachEvent ? body.attachEvent('onmousedown', listener_click) : body.addEventListener('mousedown', listener_click, false);
				listener_load();
			}, 200);
		});
	}

	window.ilike_tj = function(m, mt){
		send({m: m, mt: mt}, true);
	};
	
})();